﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LPY.LeHealth.Service;
using Webdiyer.WebControls.Mvc;
using LPY.LeHealth.DTO;
using LPY.LeHealth.Model;
using Newtonsoft.Json;
using System.Web.Security;
using NPOI;
using System.IO;
using NPOI.SS.UserModel;
using System.Text;
namespace LPY.LeHealth.WebSite.Controllers
{
    /// <summary>
    /// 医院后台
    /// </summary>
    public class HospitalController : Controller
    {

        private OrderService orderservice;
        private UserService userService;
        private HospitalAdminService hospitaladminservice;
        private TuanOrderService tuanorderservice;
        private HospitalService hospitalservice;
        private PhysicalService physicalService;

        private static  List<LPY.LeHealth.Model.PhysicalPeople1> listRainInfo;//定义导出对象
        public HospitalController()
        {
            orderservice = new OrderService();
            userService = new UserService();
            hospitaladminservice = new HospitalAdminService();
            tuanorderservice = new TuanOrderService();
            hospitalservice = new HospitalService();
            physicalService = new PhysicalService();
            //listRainInfo = new List<PhysicalPeople1>();
        }
        //[Authorize]//授权验证
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 医院后台显示
        /// </summary>
        /// <returns></returns>
        public ActionResult HospitalBackground()
        {
            ViewBag.order = orderservice.ShowOrderHospital();
            return View();
        }

        //登录
        public ActionResult Login()
        {
            //FormsAuthentication.SignOut();
            return View();
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string name, string pwd)
        {
            var usr = hospitaladminservice.AdminLogin(name,pwd);
            if (null != usr)
            {
                Session[CommonService.AdminSessionName] = usr;
                Session["hid"] = usr.HospitalId;
                //FormsAuthentication.SetAuthCookie(name, false);//给登陆用户授权
                //Session["Userid"] = hospitaladminservice.SelectUserid(name, usr.HospitalId);//返回登录人的ID
                return RedirectToAction("Index");
            }
            else
            {
                return Content("用户名或密码错误！");
            }
        }
        /// <summary>
        /// 查看医院管理员视图
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHospitalAdmin()
        {
            return View();
        }
        /// <summary>
        /// 全部医院显示
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllHospital()
        { 
            HospitalService hospitalservice=new HospitalService();
            return Json(hospitalservice.GetAllHospitall());
        }
        /// <summary>
        /// 查看医院管理员信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetHosAdmin()
        {

            var hospitalAdmins = hospitaladminservice.GetHospitalAdmin(Convert.ToInt32(Session["hid"]));
            return Json(hospitalAdmins);
        }
        /// <summary>
        /// 根据医院Id显示团检订单
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTuanOrderByHospital()
        {
            int hid =Convert.ToInt32( Session["hid"]);
            return Json(tuanorderservice.GetTuanOrder(hid));
        }
        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult HospitalRegin() 
        {
            ViewBag.Id = new SelectList(hospitalservice.GetAllHospitall(), "Id", "Name");
            return View();
        }
        [HttpPost]
        public int Adduser()
        {
            int id =Convert.ToInt32(Request["id"]);
            string name = Request["name"];
            string pwd = Request["pwd"];
            if (hospitaladminservice.Adduser(id, name, pwd)==true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 根据ID删除医院管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteUser()
        {
            int id =Convert.ToInt32(Request["id"]);
            if (hospitaladminservice.DeleteUser(id) == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        
        /// <summary>
        /// 查看当前医院团检列表（显示5项信息）
        /// </summary>
        /// <returns></returns>
        public ActionResult Tuan()
        {
            return View();
        }
        /// <summary>
        /// 查看人员体检信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[Authorize]
        public ActionResult ShowDetail(int?id,int PageIndex=1)
        {
            if(id==null)
            {
                
                int PageSize = 5;

                ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别

                ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");

                PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.SelectOrder(Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                listRainInfo = list;//给导出对象赋值
                return View(list);//返回体检人员列表
            }
            else
            {
                ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                int PageSize =5;

                ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别

                PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.SelectComboId(id, Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                listRainInfo = list;//给导出对象赋值
                return View(list);//返回体检人员列表
            }
            

        }
        /// <summary>
        /// 根据订单编号查看订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowDetail2()
        {
            

            return View();
        }
        /// <summary>
        ///  返回订单详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetOrderById()
        {
            var id =Request["OrderId"].ToString();
            var OrderDcom = hospitaladminservice.ShowOrder(id);
            return JsonConvert.SerializeObject(OrderDcom);//将集合转换为json字符串
        }
        [HttpPost]
        /// <summary>
        /// 删除订单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DelDetails()
        {
            int id = Convert.ToInt32(Request["orderid"]);
            if(hospitaladminservice.DelDetail(id)>0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 按订单号和日期查询订单
        /// </summary>
        /// <param name="ExamName"></param>
        /// <param name="datetime1"></param>
        /// <param name="datetime2"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectDetails(string ExamName, string datetime1, string datetime2,int?StateDemoId,int PageIndex=1)
        {
           if(ExamName==null || datetime1==null || datetime2==null)
           {
               ExamName = "";
               datetime1 = "";
               datetime2 = "";
           }
            if (StateDemoId != 4)
            {
                int StateId =Convert.ToInt32( StateDemoId);//获取订单状态

                    
                    if (ExamName !="" || datetime2 !="" || datetime1 !="")
                    {
                        ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                        int PageSize = 5;//定义每页的记录数
                        ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别
                        PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.SelectState(StateId, datetime1, datetime2, Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                        listRainInfo = list;//给导出对象赋值
                        return View("ShowDetail", list);
                    }
                    else
                    {
                        ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                        ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别
                        int PageSize = 5;//定义每页的记录数
                        PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.SelectStateId(StateId, Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                        listRainInfo = list;
                        return View("ShowDetail", list);
                    }
                
            }

            else
            {
                if (ExamName != "" || datetime2 !="" || datetime1 !="")
                {
                    ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                    ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别
                    int PageSize =5;//定义每页的记录数

                    PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.Selectorder(ExamName, datetime1, datetime2, Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                    listRainInfo = list;//给导出对象赋值
                    return View("ShowDetail", list);
                }
                else if (ExamName ==""|| datetime2 =="" || datetime1 =="")
                {
                    ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                    ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别
                    int PageSize =5;

                    PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.SelectOrder(Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                    listRainInfo = list;//给导出对象赋值
                    return View("ShowDetail", list);//返回体检人员列表
                }
                else
                {
                    ViewBag.StateDemoId = new SelectList(hospitaladminservice.SelectState(), "StateDemoId", "StateName");
                    ViewBag.Id = hospitaladminservice.SelectDcom(Convert.ToInt32(Session["hid"]));//绑定类别
                    int PageSize =5;//定义每页的记录数

                    PagedList<LPY.LeHealth.Model.PhysicalPeople1> list = hospitaladminservice.Selectorder(datetime1, datetime2, Convert.ToInt32(Session["hid"])).ToPagedList<LPY.LeHealth.Model.PhysicalPeople1>(PageIndex, PageSize);
                    listRainInfo = list;//给导出对象赋值
                    return View("ShowDetail", list);
                }
            }


        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditDetails(string id)
        {
            Order der = hospitaladminservice.ShowOrderState(id);//获取订单状态

            if(der!=null)
            {
                switch (der.State)
                {
                    case 0:
                        if (hospitaladminservice.UpdateState(id, 1))
                        {
                            return Content("<script>alert('订单"+id+"已改为待预约状态!');location.href='/Hospital/ShowDetail'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('状态修改失败!');location.href='/Hospital/ShowDetail'</script>");
                        }
                        
                    case 1:
                        if (hospitaladminservice.UpdateState(id, 2))
                        {
                            return Content("<script>alert('订单" + id + "已改为待体检状态!');location.href='/Hospital/ShowDetail'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('状态修改失败!');location.href='/Hospital/ShowDetail'</script>");
                        }
                     
                    case 2:
                        if (hospitaladminservice.UpdateState(id, 3))
                        {
                            return Content("<script>alert('订单" + id + "已改为体检完成状态!');location.href='/Hospital/ShowDetail'</script>");
                        }
                        else
                        {
                            return Content("<script>alert('状态修改失败!');location.href='/Hospital/ShowDetail'</script>");
                        }
                    case 3:

                       return Content("<script>alert('订单" + id + "体检流程已走完,不能再修改!');location.href='/Hospital/ShowDetail'</script>");
                        
              
                    
                }
            }
            return View("ShowDetail");
        }

        /// <summary>
        /// 体检项管理（首页）
        /// </summary>
        //[Authorize]
        public ActionResult PhysicalItem(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            var hospitals = physicalService.GetPhysicalItemList(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Data = hospitals;
            ViewBag.PageSize = pageSize;

            return View();
        }

        /// <summary>
        /// 修改体检项目
        /// </summary>
        /// <param name="physical"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditPhysical(PhysicalItem physical)
        {
            bool result = physicalService.UpdatePhysicalItem(physical);
            if (result == true)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }

        }

        /// <summary>
        /// 获取体检项目信息
        /// </summary>
        /// <param name="id">体检项目id</param>
        /// <returns>体检项目信息</returns>
        public ActionResult GetPhysical(int id)
        {
            var model = physicalService.GetPhysicalItemById(id);
            if (null != model)
            {
                return Json(new { Code = 1, Data = model, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 1, Msg = "处理失败！" });
            }
        }

        /// <summary>
        /// 添加体检项目
        /// </summary>
        /// <param name="physical"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPhysicalItem(PhysicalItem physical)
        {
            var result = false;
            result = physicalService.AddPhysicalItem(physical);

            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        /// <summary>
        /// 删除体检项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PhysicalItemDelete(int id)
        {
            var result = physicalService.DeletePhysicalItemById(id);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        //体检套餐
        public ActionResult PhysicalCombo(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            //获取体检列表
            var models = physicalService.GetPhysicalCombo(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Data = models;
            ViewBag.PageSize = pageSize;

            //获取医院列表
            var hos = hospitalservice.GetAllHospitall();
            ViewBag.Hospitals = hos;

            //获取体检类型列表
            var combos = physicalService.GetAllComboType();
            ViewBag.Combos = combos;

            //获取体检项目列表
            var items = physicalService.GetAllPhysicalItem();
            ViewBag.Items = items;

            return View();
        }

        //删除套餐
        public ActionResult PhysicalDelete(int id)
        {
            var result = physicalService.DeletePhysicalById(id);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }
        [HttpPost]
        //添加套餐
        public JsonResult PhysicalAdd(string Name, int Hospital, int ComboTypeId, string Price, string Appropriate, string Details, int Items)
        {

            double Price_dou = 0;
            if (!string.IsNullOrEmpty(Price))
            {
                Price_dou = double.Parse(Price);
            }
            var result = false;
            result = physicalService.AddComboSingle(Name, Hospital, ComboTypeId, Price_dou, Appropriate, Details, Items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }


        //添加体检套餐
        public ActionResult PhysicalComboAdd(string Name, int Hospital, int ComboTypeId, double Price, string Appropriate, string Details, List<int> Items)
        {
            var result = false;
            result = physicalService.AddCombo(Name, Hospital, ComboTypeId, Price, Appropriate, Details, Items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        //编辑套餐
        public ActionResult EditComboSingle(int id, string name, int hospital, int comboTypeId, double price, string appropriate, string details, int items)
        {
            var result = false;
            var item = new List<int>();
            item.Add(items);
            result = physicalService.EditCombo(id, name, hospital, comboTypeId, price, appropriate, details, item);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }



        //编辑体检套餐
        public ActionResult EditCombo(int id, string name, int hospital, int comboTypeId, double price, string appropriate, string details, List<int> items)
        {
            var result = false;
            result = physicalService.EditCombo(id, name, hospital, comboTypeId, price, appropriate, details, items);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }

        public ActionResult GetCombo(int id)
        {
            Combo data = physicalService.GetCombo(id);
            if (null != data)
            {
                return Json(new { Code = 1, Msg = "处理成功！", Data = data });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！", Data = data });
            }
        }

        /// <summary>
        /// 批量审批
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public int PUpdate()
        {
            int StateIdd = int.Parse(Request["StateDemoId"]);
            if(StateIdd!=4)
            {
                string result = Request["Orderid"];//截取字符串

                string[] reg = result.Split(',');
               
                foreach(var item in reg)
                {
                    hospitaladminservice.PupdateState(item, StateIdd);
                }

                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 导出体检订单信息表
        /// </summary>
        /// <returns></returns>
        public FileResult SetFileDD()
        {
            if(listRainInfo!=null)
            {
                if (listRainInfo.Count > 0)
                {
                    //创建Excel文件的对象
                    NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                    //添加一个sheet
                    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
                    //获取list数据
                    //List<LPY.LeHealth.Model.PhysicalPeople1> listRainInfo = m_BLL.GetSchoolListAATQ(schoolname);
                    //给sheet1添加第一行的头部标题
                    NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                    row1.CreateCell(0).SetCellValue("订单号");
                    row1.CreateCell(1).SetCellValue("体检人");
                    row1.CreateCell(2).SetCellValue("套餐名称");
                    row1.CreateCell(3).SetCellValue("套餐价格");
                    row1.CreateCell(4).SetCellValue("预约时间");
                    row1.CreateCell(5).SetCellValue("订单状态");
                    row1.CreateCell(6).SetCellValue("预约人");
                    row1.CreateCell(7).SetCellValue("体检人身份证号");
                    //将数据逐步写入sheet1各个行
                    for (int i = 0; i < listRainInfo.Count; i++)
                    {
                        NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                        rowtemp.CreateCell(0).SetCellValue(listRainInfo[i].OrderId.ToString());
                        rowtemp.CreateCell(1).SetCellValue(listRainInfo[i].Name.ToString());
                        rowtemp.CreateCell(2).SetCellValue(listRainInfo[i].ComBomName.ToString());
                        rowtemp.CreateCell(3).SetCellValue(listRainInfo[i].ComPrice.ToString());
                        rowtemp.CreateCell(4).SetCellValue(listRainInfo[i].AppointmentTime.ToString());
                        rowtemp.CreateCell(5).SetCellValue(listRainInfo[i].State.ToString());
                        rowtemp.CreateCell(6).SetCellValue(listRainInfo[i].Yname.ToString());
                        rowtemp.CreateCell(7).SetCellValue(listRainInfo[i].SfAdd.ToString());
                    }
                    // 写入到客户端 
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    book.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    //listRainInfo = null;//导出数据后清空集合对象
                    return File(ms, "application/vnd.ms-excel", "体检人员订单表.xls");
                }
                else
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    return File(ms, "application/Response.write", "无数据导出");
                }
            }
            else
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                return File(ms, "application/Response.write", "无数据导出");

                
            }

        }
    }
}